//
//  OverallView.m
//  MapProject
//
//  Created by rrk on 4/29/10.

//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "OverallView.h"
#import "HydrantAnnotation.h"
#import "sqlite3.h"
#import "HydrantDAO.h"
#import "HydrantData.h"

#define CLASS_A_BLUE_INDEX 0
#define CLASS_B_GREEN_INDEX  1
#define CLASS_C_ORANGE_INDEX  2
#define CLASS_D_RED_INDEX  3
#define CLASS_I_INDEX  4

#define CLASS_A_BLUE @"NFPA Class A"
#define CLASS_B_GREEN @"NFPA Class B"
#define CLASS_C_ORANGE @"NFPA Class C"
#define CLASS_D_RED @"NFPA Class D"
#define CLASS_I @"Inactive"
#define REVERSE_GEOCODE_URL @"http://maps.google.com/maps/geo?q=%@&output=csv"
#define URL_SUCCESS @"200"


#define DEFAULT_REGION_SPAN 0.015f
//cupertino address
#define DEFAULT_LAT_WITHOUT_GPS 37.331689
#define DEFAULT_LON_WITHOUT_GPS -122.030731

@implementation OverallView

@synthesize boundSwitch=boundSwitch_;
@synthesize boundView=boundView_;
@synthesize mapView=mapView_;
@synthesize hydrantDetailView=hydrantDetailView_;
@synthesize newEntryButton=newEntryButton_;
@synthesize cancelButton=cancelButton_;
@synthesize boundingModeLabel=boundingModeLabel_;
@synthesize nfpaClasses=nfpaClasses_;
@synthesize dao=dao_;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		
    }
    return self;
}
- (void)drawRect:(CGRect)rect {
	NSLog(@"test");
   	nfpaClasses_ = [[NSMutableArray alloc] init];
	[nfpaClasses_ addObject:@"NFPA Class A (Blue)>=1500 GPM"];
	[nfpaClasses_ addObject:@"NFPA Class B (Green)1000-1499 GPM"];
	[nfpaClasses_ addObject:@"NFPA Class C (Orange)500-999 GPM"];
	[nfpaClasses_ addObject:@"NFPA Class D (Red)<500 GPM"];
	[nfpaClasses_ addObject:@"Inactive"];
    mapView_.delegate=self;
	hydrantDetailView_.pickerView.delegate=self;	
	dao_ = [[HydrantDAO alloc]init];
	hydrants_=[dao_ getMapData];
	double minLat = [[hydrants_ valueForKeyPath:@"@min.LAT"] doubleValue];
	double maxLat = [[hydrants_ valueForKeyPath:@"@max.LAT"] doubleValue];
	double minLon = [[hydrants_ valueForKeyPath:@"@min.LON"] doubleValue];
	double maxLon = [[hydrants_ valueForKeyPath:@"@max.LON"] doubleValue];
	
	MKCoordinateRegion region;
	region.center.latitude = (maxLat + minLat) / 2.0;
	region.center.longitude = (maxLon + minLon) / 2.0;
	region.span.latitudeDelta = DEFAULT_REGION_SPAN;
	region.span.longitudeDelta = DEFAULT_REGION_SPAN;
	
	mapView_.region = region;
	
	for (NSDictionary *hydrantDict in hydrants_){
		HydrantAnnotation *annotation = [[HydrantAnnotation alloc] initWithDictionary:hydrantDict];
		[mapView_ addAnnotation:annotation];
		[annotation release];
	}
	
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation{
	
	if (mapView_.userLocation == annotation){
		return nil;
	}
	
	NSString *identifier = @"MY_IDENTIFIER";
	
	MKAnnotationView *annotationView = nil;//[mapView_ dequeueReusableAnnotationViewWithIdentifier:identifier];
	NSString *imageName=nil;
	annotationView = [[[MKAnnotationView alloc] initWithAnnotation:annotation 
												   reuseIdentifier:identifier]autorelease];
	if([annotation isMemberOfClass:[HydrantAnnotation class]]) {
		HydrantAnnotation *hydrantAnnotation=(HydrantAnnotation *)annotation;
		
		if([hydrantAnnotation.title isEqualToString:CLASS_D_RED]){
			imageName=@"smallred";
		}else if([hydrantAnnotation.title isEqualToString:CLASS_A_BLUE]){
			imageName=@"smallblue";
		}else if([hydrantAnnotation.title isEqualToString:CLASS_B_GREEN]){
			imageName=@"smallgreen";
		}
		else if([hydrantAnnotation.title isEqualToString:CLASS_C_ORANGE]){
			imageName=@"smallorange";
		}else{
			imageName=@"smallhazard";
		}	  
	} 
	[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"png"]];
	annotationView.image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"png"]];
	annotationView.canShowCallout = YES;
	annotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	annotationView.leftCalloutAccessoryView =  [[[UIImageView  alloc] initWithImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageName ofType:@"png"]]] autorelease];
	
	return annotationView;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
	[mapView_ setHidden:YES];
	[hydrantDetailView_ setHidden:NO];
	[newEntryButton_ setTitle:@"Update" forState:UIControlStateNormal];	
	[boundSwitch_ setHidden:YES];
	[boundingModeLabel_ setHidden:YES];
	[cancelButton_ setHidden:NO];
	NSNumber *latNumber = [[NSNumber alloc] initWithDouble:((HydrantAnnotation *)view.annotation).coordinate.latitude];
	NSNumber *lonNumber =[[NSNumber alloc] initWithDouble:((HydrantAnnotation *)view.annotation).coordinate.longitude];
	[hydrantDetailView_.latTextField setText:[latNumber stringValue]];
	[hydrantDetailView_.lonTextField setText:[lonNumber stringValue]];
	[hydrantDetailView_.addressTextView setText:((HydrantAnnotation *)view.annotation).subtitle];
	[hydrantDetailView_.remarksTextView setText:((HydrantAnnotation *)view.annotation).remarks];
	hydrantDetailView_.hydrantId=((HydrantAnnotation *)view.annotation).hydrantId;
	
	[lonNumber release];
	[latNumber release];
	if( [((HydrantAnnotation *)view.annotation).title  isEqualToString:CLASS_D_RED]){
		[hydrantDetailView_.pickerView selectRow:CLASS_D_RED_INDEX  inComponent:0 animated:YES];
	}else if([((HydrantAnnotation *)view.annotation).title  isEqualToString:CLASS_A_BLUE]){
		[hydrantDetailView_.pickerView selectRow:CLASS_A_BLUE_INDEX  inComponent:0 animated:YES];
	}else if([((HydrantAnnotation *)view.annotation).title  isEqualToString:CLASS_B_GREEN]){
		[hydrantDetailView_.pickerView selectRow:CLASS_B_GREEN_INDEX  inComponent:0 animated:YES];
	}else if([((HydrantAnnotation *)view.annotation).title  isEqualToString:CLASS_C_ORANGE]){
		[hydrantDetailView_.pickerView selectRow:CLASS_C_ORANGE_INDEX  inComponent:0 animated:YES];
	}else{
		[hydrantDetailView_.pickerView selectRow:CLASS_I_INDEX  inComponent:0 animated:YES];
	}
	[self resetKeyBoardOnHydrantDetailsView];
}
-(IBAction)toggleBoundMode:(UISwitch*)boundSwitch {
	if (inBoundMode) {
		inBoundMode = NO;
		[[self boundView] clearBoundingBox];
		[[self boundView] setUserInteractionEnabled:NO];
	}
	else {
		inBoundMode = YES;
		[[self boundView] setUserInteractionEnabled:YES];
	}
}
-(IBAction)cancelEntry:(UIButton*)button{
	[newEntryButton_ setTitle:@"New" forState:UIControlStateNormal];
	[mapView_ setHidden:NO];
	[hydrantDetailView_ setHidden:YES];
	[boundSwitch_ setHidden:NO];
	[boundingModeLabel_ setHidden:NO];
	[cancelButton_ setHidden:YES];
	[self resetKeyBoardOnHydrantDetailsView];
	hydrantDetailView_.latTextField.text=@"";
	hydrantDetailView_.lonTextField.text=@"";
	hydrantDetailView_.addressTextView.text=@"";
	hydrantDetailView_.remarksTextView.text=@"";
	
	
}
//
//This method sets the users current location if GPS is enable.
//If GPS is not enabled, it performed a reverese geocode lookup
//based on the entered address
//
-(IBAction)setLatLonByAddress:(UIButton*)button{
	
	double latitude = 0.0;
	double longitude = 0.0;
	
	//first check GPS
	NSLog(@"current location lat and long are below");
	
	if (mapView_.userLocation.location.coordinate.latitude!=DEFAULT_LAT_WITHOUT_GPS &&
		mapView_.userLocation.location.coordinate.longitude!=DEFAULT_LON_WITHOUT_GPS){
		latitude=mapView_.userLocation.location.coordinate.latitude;
		longitude=mapView_.userLocation.location.coordinate.longitude;
	}
	else if (hydrantDetailView_.addressTextView.text !=nil) {
		NSError* error;
		NSString *urlString = [NSString stringWithFormat:REVERSE_GEOCODE_URL, 
							   [hydrantDetailView_.addressTextView.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
		NSString *locationString = [NSString  stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
		NSArray *listItems = [locationString componentsSeparatedByString:@","];
		
		
		
		if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:URL_SUCCESS]) {
			latitude = [[listItems objectAtIndex:2] doubleValue];
			longitude = [[listItems objectAtIndex:3] doubleValue];
			
		}
		else {
			//Show error alert
		}
		CLLocationCoordinate2D location;
		location.latitude = latitude;
		location.longitude = longitude;
		
	}else{
		
		//show alert
		
	}
	NSString *latStr =[NSString stringWithFormat:@"%f",latitude];
	NSString *lonStr =[NSString stringWithFormat:@"%f",longitude];
	[hydrantDetailView_.latTextField setText:latStr];
	[hydrantDetailView_.lonTextField setText:lonStr];
	[self resetKeyBoardOnHydrantDetailsView];
}

-(IBAction)toggleDataEntryMode:(UIButton*)button{
	if ([newEntryButton_.titleLabel.text isEqualToString:@"New"]) {
		[mapView_ setHidden:YES];
		[hydrantDetailView_ setHidden:NO];
		[newEntryButton_ setTitle:@"Save" forState:UIControlStateNormal];	
		[boundSwitch_ setHidden:YES];
		[boundingModeLabel_ setHidden:YES];
		[cancelButton_ setHidden:NO];
		[self resetKeyBoardOnHydrantDetailsView];
		
	}else if([newEntryButton_.titleLabel.text isEqualToString:@"Update"] ){
		[newEntryButton_ setTitle:@"New" forState:UIControlStateNormal];
		[mapView_ setHidden:NO];
		[hydrantDetailView_ setHidden:YES];
		[boundSwitch_ setHidden:NO];
		[boundingModeLabel_ setHidden:NO];
		[cancelButton_ setHidden:YES];
		
		HydrantData *data = [[HydrantData alloc]init];
		data.address=hydrantDetailView_.addressTextView.text;
		NSNumberFormatter *formatter =[[NSNumberFormatter alloc]init];
		[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
		NSNumber *latNumber=[formatter numberFromString:hydrantDetailView_.latTextField.text];
		NSNumber *lonNumber=[formatter numberFromString:hydrantDetailView_.lonTextField.text];
		data.lat=latNumber;
		data.lon=lonNumber;
		data.hydrantId=hydrantDetailView_.hydrantId;
		data.remarks=hydrantDetailView_.remarksTextView.text;
		data = [self getGPMValues:data];
		[formatter release];
		//save her
		[dao_ updateHydrantData:data];
		[self updateMap];
		//then clear
		[self resetKeyBoardOnHydrantDetailsView];
		hydrantDetailView_.latTextField.text=@"";
		hydrantDetailView_.lonTextField.text=@"";
		hydrantDetailView_.addressTextView.text=@"";
		hydrantDetailView_.remarksTextView.text=@"";
		
		
	}
    else {
		[newEntryButton_ setTitle:@"New" forState:UIControlStateNormal];
		[mapView_ setHidden:NO];
		[hydrantDetailView_ setHidden:YES];
		[boundSwitch_ setHidden:NO];
		[boundingModeLabel_ setHidden:NO];
		[cancelButton_ setHidden:YES];
		HydrantData *data = [[HydrantData alloc]init];
		data.address=hydrantDetailView_.addressTextView.text;
		NSNumberFormatter *formatter =[[NSNumberFormatter alloc]init];
		[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
		NSNumber *latNumber=[formatter numberFromString:hydrantDetailView_.latTextField.text];
		NSNumber *lonNumber=[formatter numberFromString:hydrantDetailView_.lonTextField.text];
		data.lat=latNumber;
		data.lon=lonNumber;
		data.remarks=hydrantDetailView_.remarksTextView.text;
		data = [self getGPMValues:data];
		[formatter release];
		//save her
		[dao_ addHydrantData:data];
		[self updateMap];
		//then clear
		[self resetKeyBoardOnHydrantDetailsView];
		hydrantDetailView_.latTextField.text=@"";
		hydrantDetailView_.lonTextField.text=@"";
		hydrantDetailView_.addressTextView.text=@"";
		hydrantDetailView_.remarksTextView.text=@"";
		
	}
	
}
//									  
//Adjust map view per bounding box selection
//	
-(CGRect)adjustMapToRect:(CGRect)frame {
	CGPoint center;
	
	NSLog(@"Original origin      : %f, %f", frame.origin.x, frame.origin.y);
	NSLog(@"Original span        : %f, %f", frame.size.width, frame.size.height);
	NSLog(@"Absolute center      : %f, %f", (frame.origin.x + frame.size.width / 2.0), (frame.origin.y + frame.size.height / 2.0));
	/* Find the center of the bounding box, relative to a grid with x [0,1] and y [0,1] */
	center.x = (frame.origin.x + frame.size.width / 2.0) / 320.0;
	center.y = (frame.origin.y + frame.size.height / 2.0) / 415.0;
	NSLog(@"Coordinate center    : %f, %f", center.x, center.y);
	
	/* Find the span (width and height) of the bounding box, in terms of proportion of the 
	 total view height and width */
	CGSize span;
	span.width = frame.size.width / 320.0;
	span.height = frame.size.height / 415.0;
	NSLog(@"Coordinate span      : %f %f", span.width, span.height);
	
	/* Get the current MapView region */
	MKCoordinateRegion currentRegion = [mapView_ region];//[mapView_ convertRect:[mapView_ frame] toRegionFromView:mapView_];
	NSLog(@"Current Region span  : %f %f", currentRegion.span.longitudeDelta, currentRegion.span.latitudeDelta);
	NSLog(@"Current Region center: %f %f", currentRegion.center.longitude, currentRegion.center.latitude);
	
	/* Find the center of the region as it relates to a [0,1] by [0,1] grid */
	float xStart = currentRegion.center.longitude - (currentRegion.span.longitudeDelta / 2.0);
	float xCoord = (currentRegion.center.longitude - xStart) / currentRegion.span.longitudeDelta;
	float yStart = currentRegion.center.latitude - (currentRegion.span.latitudeDelta / 2.0);
	float yCoord = (currentRegion.center.latitude - yStart) / currentRegion.span.latitudeDelta;
	NSLog(@"Curr coord region cen: %f %f", xCoord, yCoord);
	
	/* Make the new region based on the bounding box's width and height */
	MKCoordinateRegion newRegion;
	newRegion.span.longitudeDelta = (span.width * currentRegion.span.longitudeDelta);
	newRegion.span.latitudeDelta = (span.height * currentRegion.span.latitudeDelta);
	newRegion.center.longitude = xStart + (currentRegion.span.longitudeDelta * center.x);
	newRegion.center.latitude = yStart + (currentRegion.span.latitudeDelta * (1 - center.y));
	NSLog(@"Potential new center: %f %f", newRegion.center.longitude, newRegion.center.latitude);
	
	/* Fit this region to the proper aspect ratio, then animate view to proper location */
	MKCoordinateRegion fitRegion = [mapView_ regionThatFits:newRegion];
	[mapView_ setRegion:fitRegion animated:YES];
	NSLog(@"New Region span      : %f %f", fitRegion.span.longitudeDelta, fitRegion.span.latitudeDelta);
	NSLog(@"New region center    : %f %f", fitRegion.center.longitude, fitRegion.center.latitude);
	NSLog(@"Per. of bounding box : %f %f", (newRegion.span.longitudeDelta / fitRegion.span.longitudeDelta), (newRegion.span.latitudeDelta / fitRegion.span.latitudeDelta));
	
	/* Prepare a new frame for the bounding box that can be used to scale & translate the old
	 bounding box*/
	CGRect newFrame;
	span.height = 415.0 * (newRegion.span.latitudeDelta / fitRegion.span.latitudeDelta);
	span.height = (span.height > 415.0) ? 415.0 : span.height;
	span.width = 320.0 * (newRegion.span.longitudeDelta / fitRegion.span.longitudeDelta);
	span.width = (span.width > 320.0) ? 320.0 : span.width;
	newFrame.size = span;
	newFrame.origin.x = (320 - newFrame.size.width) / 2.0;
	newFrame.origin.y = (415 - newFrame.size.height) / 2.0;
	return newFrame;
	
	
}

- (BOOL) textFieldShouldReturn:(UITextField *)textField{
	[textField resignFirstResponder]; 
	return YES;
}
- (BOOL) textViewShouldReturn:(UITextView *)textView{
	[textView resignFirstResponder]; 
	return YES;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {
	
	return 1;
}
//PickerViewController.m
- (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component {
	
	return [nfpaClasses_ count];
}
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
	UILabel *retval = (id)view;
	if (!retval) {
		retval= [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerView rowSizeForComponent:component].width, [pickerView rowSizeForComponent:component].height)] autorelease];
	}
	retval.text = [nfpaClasses_ objectAtIndex:row];
	retval.font = [UIFont systemFontOfSize:15];
	return retval;
}
//PickerViewController.m
- (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	
	return [nfpaClasses_ objectAtIndex:row];
}
//									  
//Updates maps with user driven changes.
//									  
-(void) updateMap{
	
	MKCoordinateRegion prevRegion = mapView_.region;
	
	[mapView_ removeAnnotations:mapView_.annotations];
	
	nfpaClasses_ = [[NSMutableArray alloc] init];
	[nfpaClasses_ addObject:@"NFPA Class A (Blue)>=1500 GPM"];
	[nfpaClasses_ addObject:@"NFPA Class B (Green)1000-1499 GPM"];
	[nfpaClasses_ addObject:@"NFPA Class C (Orange)500-999 GPM"];
	[nfpaClasses_ addObject:@"NFPA Class D (Red)<500 GPM"];
	[nfpaClasses_ addObject:@"Inactive"];
	mapView_.delegate=self;
	hydrantDetailView_.pickerView.delegate=self;	
	dao_ = [[HydrantDAO alloc]init];
	hydrants_=[dao_ getMapData];
	/*double minLat = [[hydrants_ valueForKeyPath:@"@min.LAT"] doubleValue];
	 double maxLat = [[hydrants_ valueForKeyPath:@"@max.LAT"] doubleValue];
	 double minLon = [[hydrants_ valueForKeyPath:@"@min.LON"] doubleValue];
	 double maxLon = [[hydrants_ valueForKeyPath:@"@max.LON"] doubleValue];*/
	
	
	mapView_.region = prevRegion;
	
	for (NSDictionary *hydrantDict in hydrants_){
		HydrantAnnotation *annotation = [[HydrantAnnotation alloc] initWithDictionary:hydrantDict];
		[mapView_ addAnnotation:annotation];
		[annotation release];
	}
	[mapView_ setCenterCoordinate:mapView_.region.center animated:NO];
	[self resetKeyBoardOnHydrantDetailsView];
	
}
- (HydrantData *)getGPMValues:(HydrantData *) data{									  
    
	if(data!=nil){								  
		
		if ([hydrantDetailView_.pickerView selectedRowInComponent:0]==CLASS_A_BLUE_INDEX) {
			data.nfpaClass=@"A";
			data.gpm=[[NSNumber alloc]initWithInt:1500];
		}else if([hydrantDetailView_.pickerView selectedRowInComponent:0]==CLASS_B_GREEN_INDEX) {
			data.nfpaClass=@"B";
			data.gpm=[[NSNumber alloc]initWithInt:1001];
		}else if([hydrantDetailView_.pickerView selectedRowInComponent:0]==CLASS_C_ORANGE_INDEX) {
			data.nfpaClass=@"C";
			data.gpm=[[NSNumber alloc]initWithInt:501];
		}else if([hydrantDetailView_.pickerView selectedRowInComponent:0]==CLASS_D_RED_INDEX){
			data.nfpaClass=@"D";
			data.gpm=[[NSNumber alloc]initWithInt:499];
		}else{
			data.nfpaClass=@"I";
			if (data.gpm!=0) {
				//do nothing<#statements#>
			}else{  
				data.gpm=[[NSNumber alloc]initWithInt:0];
			}
		}
	}
	return data;
}
-(void)resetKeyBoardOnHydrantDetailsView{
	[self textFieldShouldReturn:hydrantDetailView_.latTextField];
	[self textFieldShouldReturn:hydrantDetailView_.lonTextField];
	[self textViewShouldReturn:hydrantDetailView_.addressTextView];
	[self textViewShouldReturn:hydrantDetailView_.remarksTextView];
}


- (void)dealloc {
	[hydrants_ release];
	[mapView_ release];
	[boundSwitch_ release];
	[boundView_ release];
	[newEntryButton_ release];
	[cancelButton_ release];
	[nfpaClasses_ release];
	[dao_ release];
    [super dealloc];
}
@end
